import * as net from "node:net";
import * as os from "node:os";

export async function getAvailablePort(startPort: number): Promise<number> {
  return new Promise(resolve => {
    const tryPort = (port: number) => {
      const server = net.createServer();
      server.once("error", () => {
        tryPort(port + 1);
      });

      server.once("listening", () => {
        server.close(() => {
          resolve(port);
        });
      });

      server.listen(port);
    };

    tryPort(startPort);
  });
}

/**
 * 获取本机所有局域网地址
 */
export function getLanIpAddresses() {
  const interfaces = os.networkInterfaces();
  const results: string[] = [];

  for (const name of Object.keys(interfaces)) {
    const nameLower = name.toLowerCase();
    if (nameLower.includes("vmware")) {
      continue;
    }

    const addresses = interfaces[name]!.filter(it => it.family === "IPv4" && !it.internal).map(it => it.address);
    if (addresses.length > 0) {
      results.push(...addresses);
    }
  }

  return results;
}
